const app = getApp();
const api = require('../../utils/api');
const md5 = require('../../utils/md5');

Page({
    data: {
        couponList: [],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        noContent: false, //无数据
        isFinished: false, //加载结束
        pointAccount: 0,

        showQuantity: false, //兑换数量弹窗
        couponSelected: '', //选择要购买的购物券商品
        quantity: 1,
        total: 0,

        showPassword: false, //支付密码弹窗
        couponOrderId: '',
        payPassword: '',
        isSetPayPassword: true, //是否已经设置支付密码
    },
    onLoad(options) {
    },
    onShow() {
        this.setData({
            isSetPayPassword : app.globalData.userInfo.isSetPayPassword == 1 ? true : false,
        });
        
        this.getCouponData();
        this.getPointAccount();
    },

    getCouponData() { //获取购物券列表
        let params = {
            saleChannel: 0,
            couponType: 0,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post('/coupon/product/list', params)
            .then(res => {
                let list = res;

                this.setData({
                    couponList: list,
                    noContent: res.length ? false : true
                });
            })
    },
    getPointAccount() { //获取积分账户余额
        api.post(`/user/member/account`)
            .then(res => {
                this.setData({
                    pointAccount: res.balance
                });
            })
    },

    //兑换（设置数量）弹窗
    openQuantity(e) { //打开设置数量弹窗
        this.setData({
            couponSelected: e.currentTarget.dataset.item,
            showQuantity: true
        });
        this.dealSummary();
    },
    closeQuantity() { //关闭设置数量弹窗
        this.setData({
            showQuantity: false,
            quantity: 1
        });
    },

    quantityPlus() { //数量加
        let num = this.data.quantity;
        this.setData({
            quantity: num + 1
        });
        this.dealSummary();
    },
    quantityMinus() { //数量减
        if(this.data.quantity == 1) {
            return;
        }
        let num = this.data.quantity;
        this.setData({
            quantity: num - 1
        });
        this.dealSummary();
    },
    dealSummary() {
        this.setData({
            total: this.data.couponSelected.couponCredits * this.data.quantity
        });
    },
    submitOrder() {
        if(this.data.total > this.data.pointAccount) {
            wx.showToast({
                title: '您的积分余额不足',
                icon: 'none'
            });
            return;
        }
        if(!this.data.isSetPayPassword) {
            //如果没有设置支付密码，提醒去设置
            wx.showModal({
                title: '温馨提示',
                content: `您还未设置支付密码！`,
                confirmText: '去设置',
                cancelText: '晚点设置',
                success: res => {
                    if(res.confirm) {
                        wx.navigateTo({
                            url: '/pages/setPayPassword/setPayPassword',
                        })
                    } else {
                        this.closeBuyCouponBox();
                    }
                }
            });
            return;
        }
        //整理参数
        let params = {
            productId: this.data.couponSelected.id,
            couponPrice: this.data.couponSelected.couponPrice, //销售金额
            couponCredits: this.data.couponSelected.couponCredits, //销售价格(积分)
            orderQuantity: this.data.quantity,
            orderAmount: (this.data.couponSelected.couponPrice * this.data.quantity).toFixed(2), //订单总金额
            orderAmountCredit: this.data.couponSelected.couponCredits * this.data.quantity, //订单总金额（积分）
            payAmount: (this.data.couponSelected.couponPrice * this.data.quantity).toFixed(2), //应付金额
            payAmountCredits: this.data.couponSelected.couponCredits * this.data.quantity, //实付金额（积分）
        }
        api.post('/coupon/order/add', params)
            .then(res => {
                this.setData({
                    couponOrderId: res,
                    showPassword: true,
                });
            })
    },
    cancelOrder() { //取消订单
        wx.showModal({
            title: '温馨提示',
            content: `您是否确认取消积分兑券订单？`,
            success: res => {
                if(res.confirm) {
                    api.post('/coupon/order/cancel?orderId=' + this.data.couponOrderId)
                        .then(() => {
                            wx.showToast({
                                title: '订单已取消',
                                icon: 'none'
                            });
                            this.closePassword();
                            this.closeQuantity();
                        })
                }
            }
        });
    },

    //支付密码弹窗
    bindinput(e) { //输入框监听
        let item = e.currentTarget.dataset.item;
        let val = e.detail.value;
        this.setData({
            [item]: val
        });
    },
    submitPassword() { //提交支付密码
        if(!this.data.payPassword) {
            wx.showToast({
                title: `请输入支付密码`,
                icon: 'none'
            });
            return;
        }
        
        let password = this.data.payPassword;
        api.post('/payment/credits/pay', {
            orderId: this.data.couponOrderId,
            abc: md5.md5(password)
        })
            .then(() => {
                wx.showToast({
                    title: '购券成功',
                    icon: 'success'
                });

                this.closePassword();
                this.closeQuantity();
                this.getPointAccount();
            })
    },
    closePassword() { //关闭支付密码弹窗
        this.setData({
            payPassword: '',
            showPassword: false,
        });
    },
})